/**
 *
 */

package com.borqs.music.ui.bpc;

import static com.borqs.music.util.MusicUtils.DownloadDefs.DOWNLOAD_INTENT_KEY_NEED_SHOW_TOAST;
import static com.borqs.music.util.MusicUtils.DownloadDefs.DOWNLOAD_INTENT_KEY_SINGLE_ITEM;

import com.borqs.music.DownloadService;
import com.borqs.music.R;
import com.borqs.music.executor.MusicExecutor;
import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskAdapter;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.model.DownloadItem;
import com.borqs.music.model.SongInfo;
import com.borqs.music.tasks.GetSingleSongTask;
import com.borqs.music.tasks.UpdateOnlineFavorTask;
import com.borqs.music.ui.AudioPreview;
import com.borqs.music.ui.online.OnlineTrackBrowserActivity;
import com.borqs.music.util.AccountUtils;
import com.borqs.music.util.AsyncImageLoader;
import com.borqs.music.util.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

/**
 * @author b431
 */
public class MusicDetailsActivity extends Activity {
    public static final String URI = "borqs://music/details";
    public static final String ID = "id"; // call back from Stream.

    private ImageView iconView;
    private TextView trackView;
    private TextView artistView;
    private TextView albumView;
    private Button btnPreview;
    private Button btnDownload;
    private Button btnFavor;
    private SongInfo song;

    private String mUnknownArtist;
    private String mUnknownAlbum;
    private Bitmap mDefaultAlbumIcon;
    private AsyncImageLoader imageLoader;
    private String mTicket;

    private Toast mToast;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_details);
        mUnknownArtist = getString(R.string.unknown_artist_name);
        mUnknownAlbum = getString(R.string.unknown_album_name);
        mDefaultAlbumIcon = BitmapFactory.decodeResource(getResources(),
                R.drawable.albumart_mp_unknown_list);
        int defaultWidth = mDefaultAlbumIcon.getWidth();
        int defaultHeight = mDefaultAlbumIcon.getHeight();
        imageLoader = new AsyncImageLoader(defaultWidth, defaultHeight);

        iconView = (ImageView) findViewById(R.id.album);
        trackView = (TextView) findViewById(R.id.trackname);
        artistView = (TextView) findViewById(R.id.artistname);
        albumView = (TextView) findViewById(R.id.albumname);
        btnPreview = (Button) findViewById(R.id.preview);
        btnPreview.setOnClickListener(btnListener);
        btnDownload = (Button) findViewById(R.id.download);
        btnDownload.setOnClickListener(btnListener);
        btnFavor = (Button) findViewById(R.id.add_favor);
        btnFavor.setOnClickListener(btnListener);
        // let onNewIntent to handle
        Intent intent = getIntent();
        onNewIntent(intent);

        mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
    }

    void showToast(int msgId){
        mToast.setText(msgId);
        mToast.show();
    }

    @Override
    public void onNewIntent(Intent intent) {
        String songIdStr = intent.getStringExtra(ID);
        int songId = -1;
        try {
            songId = Integer.parseInt(songIdStr);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
            songId = -1;
        }
        if (songId < 0) {
            finish();
            return;
        }

        iconView.setImageResource(R.drawable.albumart_mp_unknown);
        artistView.setText("");
        albumView.setText("");
        trackView.setText("");

        mTicket = AccountUtils.getUserData(this,
                AccountUtils.BORQS_ACCOUNT_OPTIONS_KEY_SESSION);
        GetSingleSongTask task = new GetSingleSongTask(infoListener, songId);
        MusicExecutor.getInstance().execute(task);
    }

    private void updateTextViews() {
        String artist = song.artist;
        if (artist == null || artist.length() == 0 || artist.equals(MediaStore.UNKNOWN_STRING)) {
            artistView.setText(mUnknownArtist);
        } else {
            artistView.setText(artist);
        }
        String album = song.album;
        if (album == null || album.length() == 0 || album.equals(MediaStore.UNKNOWN_STRING)) {
            albumView.setText(mUnknownAlbum);
        } else {
            albumView.setText(album);
        }

        trackView.setText(song.title);
    }

    private View.OnClickListener btnListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (song == null) {
                return;
            }

            if (v.getId() == R.id.preview) {
                Uri uri = Uri.parse(song.fileUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.setClass(MusicDetailsActivity.this, AudioPreview.class);
                startActivity(intent);
                return;
            }

            if (v.getId() == R.id.download) {
                downloadSingleSong(MusicDetailsActivity.this, song);
                return;
            }

            if (v.getId() == R.id.add_favor) {
                if (song.isFavorite) {
                    showToast(R.string.details_already_favor);
                } else {
                    UpdateOnlineFavorTask updateOnlineFavor = new UpdateOnlineFavorTask(
                            favorListener, mTicket, song.id + "", true);
                    MusicExecutor.executeTask(updateOnlineFavor);
                }
                return;
            }
        }
    };

    public static void downloadSingleSong(Context context, SongInfo song) {
        String fileName = OnlineTrackBrowserActivity.getFileName(song);
        DownloadItem item = new DownloadItem(song.id, song.title, song.artist, fileName,
                song.fileMd5, song.isFavorite);
        Intent intent = new Intent(context, DownloadService.class);
        intent.setAction(DownloadService.ACTION_START_DOWNLOAD);
        intent.putExtra(DOWNLOAD_INTENT_KEY_SINGLE_ITEM, item);
        intent.putExtra(DOWNLOAD_INTENT_KEY_NEED_SHOW_TOAST, true);
        context.startService(intent);
    }

    private static final int DIALOG_PROGRESS = 0;

    public Dialog onCreateDialog(int id, Bundle bundle) {
        if (id == DIALOG_PROGRESS) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setIcon(android.R.drawable.ic_dialog_info);
            dialog.setTitle(R.string.dialog_loading_songs_title);
            dialog.setMessage(getString(R.string.dialog_loading_songs_message));
            dialog.setCancelable(true);
            return dialog;
        }

        return null;
    }

    private static final int MSG_SONG_START = 0;
    private static final int MSG_SONG_DONE = 1;
    private static final int MSG_SONG_FAILED = 2;
    private static final int MSG_SONG_IMAGE = 3;
    private static final int MSG_FAVOR_FAILED = 4;
    private static final int MSG_FAVOR_SUCCESS = 5;
    private Handler eventHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SONG_START:
                    btnDownload.setEnabled(false);
                    btnPreview.setEnabled(false);
                    btnFavor.setEnabled(false);
                    showDialog(DIALOG_PROGRESS);
                    break;
                case MSG_SONG_FAILED:
                    btnDownload.setEnabled(false);
                    btnPreview.setEnabled(false);
                    btnFavor.setEnabled(false);
                    artistView.setText(msg.arg1);
                    dismissDialog(DIALOG_PROGRESS);
                    break;
                case MSG_SONG_DONE:
                    dismissDialog(DIALOG_PROGRESS);
                    @SuppressWarnings("unchecked")
                    List<SongInfo> songs = (List<SongInfo>) msg.obj;
                    if (songs.size() > 0) {
                        song = songs.get(0);
                        updateTextViews();
                        if (song.imgUrl != null && song.imgUrl.length() > 0) {
                            Bitmap bitmap = imageLoader.loadBitmap(song.imgUrl, imageCallback);
                            if (bitmap != null) {
                                iconView.setImageBitmap(bitmap);
                            }
                        }

                        btnDownload.setEnabled(true);
                        btnPreview.setEnabled(true);
                        btnFavor.setEnabled(true);
                    } else {
                        Message failedMsg = obtainMessage(MSG_SONG_FAILED);
                        failedMsg.arg1 = R.string.details_song_deleted;
                        sendMessage(failedMsg);
                    }
                    break;
                case MSG_SONG_IMAGE:
                    if (msg.obj != null) {
                        Drawable dr = (Drawable) msg.obj;
                        iconView.setImageDrawable(dr);
                    }
                    break;
                case MSG_FAVOR_FAILED:
                    showToast(R.string.update_favorite_failed);
                    break;
                case MSG_FAVOR_SUCCESS:
                    song.isFavorite = true;
                    showToast(R.string.add_into_myfavorite_msg);
                    break;
            }
        }
    };

    private ImageCallback imageCallback = new ImageCallback() {
        public void imageLoaded(Bitmap imageBitmap, String imageUrl) {
            iconView.setImageBitmap(imageBitmap);
        }
    };

    TaskListener infoListener = new TaskAdapter() {
        @Override
        public void onStart(Task task) {
            eventHandler.sendEmptyMessage(MSG_SONG_START);
        }

        @Override
        public void onDone(Task task) {
            Message msg = eventHandler.obtainMessage(MSG_SONG_DONE);
            msg.obj = task.getResult();
            msg.sendToTarget();
        }

        @Override
        public void onFail(Task task) {
            Message msg = eventHandler.obtainMessage(MSG_SONG_FAILED);
            msg.arg1 = R.string.details_load_failed;
            eventHandler.sendMessage(msg);
        }

        @Override
        public void onCancel(Task task) {
            finish();
        }
    };

    TaskListener favorListener = new TaskAdapter() {
        @Override
        public void onFail(Task task) {
            eventHandler.sendEmptyMessage(MSG_FAVOR_FAILED);
        }

        @Override
        public void onDone(Task task) {
            eventHandler.sendEmptyMessage(MSG_FAVOR_SUCCESS);
        }
    };
}
